import data from "./data.js"
const main = async () => {
    // let code_list = await getCode()
    console.log(data.shjys_data, data.szjys_data)
    let code_list = data.szjys_data;
    
    let sign = "hs"
    let name_arr = [];
    for (let i = 0; i < code_list.length; i++) {
        const code = code_list[i][0];
        const name = code_list[i][1];

        window[`quotebridge_v6_line_${sign}_${code}_01_all`] = async (res) => {
            let macd = await showPrice(res.dates, res.price, res.volumn, 50)

            let last_index = macd.macd.length - 1
            if(
                macd.macd[last_index] > macd.macd[last_index - 1] &&
                macd.macd[last_index - 1] > macd.macd[last_index -2] &&
                macd.macd[last_index -2] > macd.macd[last_index - 3] &&
                macd.macd[last_index] > 0 &&
                macd.macd[last_index - 1] < 0
            ){
                console.log(name)
                name_arr.push(name)
            }
        }

        try {
            var url = `https://d.10jqka.com.cn/v6/line/${sign}_${code}/01/all.js`
            await addScript(url)
        } catch (error) {
            await sleep(3000)
            try {
                var url = `https://d.10jqka.com.cn/v6/line/${sign}_${code}/01/all.js`
                await addScript(url)
            } catch (error) {
                await sleep(3000)
                var url = `https://d.10jqka.com.cn/v6/line/${sign}_${code}/01/all.js`
                await addScript(url)
            }
        }
    }
    console.log(name_arr.join())

    function getCode(){
        return new Promise((resolve,reject) => {
            window[`jsonpCallback84379775`] = (res) => {
                console.log(JSON.stringify(res.list))
                resolve(res.list)
            }

            addScript("https://yunhq.sse.com.cn:32042/v1/sh1/list/exchange/equity?callback=jsonpCallback84379775")
        })
    }
    
    function addScript(s){
        return new Promise((resolve, reject) => {
            const script = document.createElement("script")
            script.src = s
            document.head.append(script)
            script.onload = () => {
                resolve()
            }
            script.onerror = () => {
                reject()
            }
        })
    }

    function chunkArray(arr, chunkSize = 4) {
        const result = [];
        for (let i = 0; i < arr.length; i += chunkSize) {
            result.push(arr.slice(i, i + chunkSize));
        }
        return result;
    }

    function showPrice(d, p, v, n){
        return new Promise((resolve, reject) => {
            let dates = d.split(",");
            let len = dates.length;
            let prices = p.split(",");
            let prices_singles = chunkArray(prices, 4);
            let volumns = v.split(",")

            let price_arr = []
            for (let i = 1; i <= n; i++) {
                let index = len - i;
                let current_pricess = prices_singles[index].map(n => Number(n))
                let low_price = current_pricess[0]
                let high_price = current_pricess[0] + current_pricess[2]
                let end_price = current_pricess[0] + current_pricess[3]
                let start_price = current_pricess[0] + current_pricess[1]

                // console.log(`日期：${dates[index]},开盘价格：${start_price},收盘价格：${end_price},最低价格：${low_price},最高：${high_price},成交：${volumns[index]}`)

                price_arr.push(end_price)
            }
            
            
            let price_arr_num = price_arr.map(a => a / 100).reverse();

            resolve(calculateMACD(price_arr_num))
        })
    }

    // 计算MACD
    function calculateMACD(prices) {
        const ema12 = calculateEMA(prices, 12);
        const ema26 = calculateEMA(prices, 26);
        
        // 计算DIF
        const dif = [];
        for (let i = 0; i < prices.length; i++) {
            if (ema12[i] === null || ema26[i] === null) {
                dif.push(null);
            } else {
                dif.push(ema12[i] - ema26[i]);
            }
        }
        
        // 计算DEA (DIF的9日EMA)
        const dea = calculateEMA(dif.filter(val => val !== null), 9);
        // 补齐前面的空值
        while (dea.length < dif.length) {
            dea.unshift(null);
        }
        
        // 计算MACD柱
        const macd = [];
        for (let i = 0; i < prices.length; i++) {
            if (dif[i] === null || dea[i] === null) {
                macd.push(null);
            } else {
                macd.push((dif[i] - dea[i]) * 2);
            }
        }
        
        return { ema12, ema26, dif, dea, macd };
    }

    // 计算EMA
    function calculateEMA(prices, period) {
        const k = 2 / (period + 1);
        const ema = [];
        
        // 第一个EMA是简单移动平均
        let sum = 0;
        for (let i = 0; i < period; i++) {
            sum += prices[i];
            ema.push(null); // 前期数据不足，设为null
        }
        ema[period-1] = sum / period;
        
        // 计算后续的EMA值
        for (let i = period; i < prices.length; i++) {
            ema.push(prices[i] * k + ema[i-1] * (1 - k));
        }
        
        return ema;
    }

    function sleep(ms) {
        return new Promise(resolve => setTimeout(resolve, ms));
    }
}

main()